package com.gitee.somenvm.ninerpgitem.util

import taboolib.common5.format

/**
 * 数学计算工具
 * com.gitee.somenvm.ninerpgitem.util
 *
 * @author  SomeNvM
 * @date  2022/12/17 22:13
 */
object MathUtil {
    /**
     * 返回字符串算式的结果
     */
    fun String.countNum(): Double {

        val numArray: CharArray = toCharArray()
        val number = ArrayList<String>()

        var num = ""
        for (n in numArray.indices) {
            val char = numArray[n].toString()
            when (char) {
                "-", "+", "*", "/" -> {
                    if (num.isNotEmpty()) {
                        number.add(num)
                        num = ""
                    }
                    num += char
                    number.add(num)
                    num = ""
                }

                else -> {
                    num += char
                    if (n == numArray.size - 1) {
                        number.add(num)
                    }
                }
            }

        }
        return num(number)
    }

    private fun num(number: ArrayList<String>): Double {
        var one: Float
        var two: Float
        var result: Float
        var count = 0
        var total = 0.0
        var flag = 0
        //计算出有乘除个数
        (0 until number.size).filter { number[it] == "*" || number[it] == "/" }.forEach { _ -> count += 1 }

        for (m in 0..count) {
            loop@ for (n in 0..number.size - 2) {
                when (val char = number[n]) {
                    "*", "/" -> {
                        one = number[n - 1].toFloat()
                        two = number[n + 1].toFloat()
                        result = if ("*" == char) one * two else one / two
                        number[n] = result.toString()

                        number.removeAt(n + 1)
                        number.removeAt(n - 1)
                        break@loop
                    }
                }

            }
        }

        for (m in 0 until number.size) {
            val char: String = number[m]
            when (char) {
                "+", "-" -> flag = if ("+" == char) 0 else 1
                else -> {
                    if (flag == 0) total += number[m].toDouble().format(2)
                    else total -= number[m].toDouble().format(2)
                }
            }
        }
        return total
    }
}